package puntaelena.facilitylocation.hillclimbing.solver.agents;

import jfuzzyprincepless.negotiation.INegotiationContext;
import jfuzzyprincepless.algorithm.structure.services.IWhileService;
import puntaelena.facilitylocation.hillclimbing.solver.services.IFcltLocDataService;

public class CollaboratingFacilityAgent
	extends BaseFacilityAgent
{
	private FacilityCoalition coalition;

	public CollaboratingFacilityAgent(int facility) {
		super(facility);
	}

	@Override
	public boolean negotiate(
		INegotiationContext context
	) {
		IFcltLocDataService flServ =
			context.getService(IFcltLocDataService.class);
		IWhileService whileService =
			context.getService(IWhileService.class);
		if (flServ.getFcltOpen()[facility]) {
			return whileService.isAgentAlive(this);
		}

		FacilityCoalition coalition = getCoalition(flServ);
		if (!coalition.isOwner(this)) { // TODO: add servise of alive agents
			return whileService.isAgentAlive(this);
		}

		return coalition.coalitionNegotiate(context);
	}

	public FacilityCoalition getCoalition(IFcltLocDataService flServ) {
		if (coalition == null) {
			coalition = new FacilityCoalition(this, flServ);
		}
		return coalition;
	}

	public void setCoalition(FacilityCoalition coalition) {
		this.coalition = coalition;
	}

	@Override
	public String toString() {
		return "ColAg: " + facility;
	}
}
